import { isQtClient } from './util'

import QWebChannel from './qwebchannel'
export let Channel: any = null
let socket: any = null
let connectedCb: any = null
let disconnectedCb: any = null
export const initQt = (cb = () => {}, db = () => {}) => {
	if (!isQtClient) {
		console.log('现在是外部浏览器模式')
		window.qt = {
			webChannelTransport: {
				send() {
					console.log(`QWebChannel simulator activated !`)
				},
			},
		}
	}

	connectedCb = cb
	disconnectedCb = db
	try {
		link(
			(socket: any) => {
				const QWC = QWebChannel as any
				const webc = new QWC(socket, (channel: any) => {
					Channel = channel.objects
					connectedCb()
				})
				return webc
			},
			(error: any) => {
				console.log('socket error', error)
				disconnectedCb()
			}
		)
	} catch (error) {
		console.log('socket exception:', error)
		disconnectedCb()
		Channel = undefined
	}
}

const link = (resolve: any, reject: any) => {
	console.log('link...')

	const baseUrl = 'ws://localhost:12312'
	const sk = new WebSocket(baseUrl)
	socket = sk
	socket.onopen = () => {
		resolve(socket)
	}
	socket.onerror = (error: any) => {
		console.log('error-scoket')
		// window.location = "/login";
		reject(error)
	}
	socket.onclose = (error: any) => {
		console.log('close-scoket')
		reject(error)
	}
}
